/** 
 * Function.java
 * @author Lex
 * 2007-8-25 ����12:10:03
 */
package fun.ui.canvas;

import fun.parser.EvaluationException;
import fun.parser.ast.node.base.Expression;
import fun.symtable.FixsizeSymbolTable;
import fun.symtable.FunctionEntry;
import fun.symtable.SymbolTable;
import fun.symtable.VariableEntry;

public class Function extends FunctionEntry {
	private FunctionEntry functionEntry = null;
	private SymbolTable functionSymbolTable = null;
	private VariableEntry argumentEntry = null;

	public Function(FunctionEntry fe) {
		super(fe.getName(), fe.getParameters(), fe.getExpression());
		this.functionEntry = fe;
	}

	public double getValue(SymbolTable symtable, double argument) {
		this.getArgumentEntry(symtable).setValue(argument);
		// ���㺯��ֵ
		Expression expr = functionEntry.getExpression();
		try {
			return expr.getValue(functionSymbolTable);
		} catch (EvaluationException e) {
			e.printStackTrace();
			return 0;
		}
	}

	private VariableEntry getArgumentEntry(SymbolTable symtable) {
		if (null == this.argumentEntry) {
			String arg = functionEntry.getParameters()[0];
			// ����βε���ű�
			argumentEntry = getFunctionSymbolTable(symtable).setVariable(arg, 0);
		}
		return this.argumentEntry;
	}

	private SymbolTable getFunctionSymbolTable(SymbolTable symtable) {
		if (null == this.functionSymbolTable) {
			// �����β�-ʵ�η�ű�
			functionSymbolTable = new FixsizeSymbolTable(functionEntry.toString(), 0, 1);
			functionSymbolTable.setParent(symtable);
		}
		return this.functionSymbolTable;
	}
}
